//package plugin.demo;
//
//import com.intellij.openapi.actionSystem.*;
//import com.intellij.openapi.editor.Document;
//import com.intellij.openapi.editor.Editor;
//import com.intellij.openapi.editor.SelectionModel;
//import com.intellij.openapi.fileEditor.FileDocumentManager;
//import com.intellij.openapi.fileEditor.OpenFileDescriptor;
//import com.intellij.openapi.module.Module;
//import com.intellij.openapi.project.Project;
//import com.intellij.openapi.roots.ProjectFileIndex;
//import com.intellij.openapi.roots.ProjectRootManager;
//import com.intellij.openapi.ui.popup.*;
//import com.intellij.openapi.util.TextRange;
//import com.intellij.openapi.util.text.StringUtil;
//import com.intellij.openapi.vfs.VirtualFile;
//import com.intellij.psi.PsiFile;
//import com.intellij.psi.PsiManager;
//import com.intellij.psi.search.FilenameIndex;
//import com.intellij.psi.search.GlobalSearchScope;
//import com.intellij.util.Consumer;
//
//import java.util.*;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
//import java.util.stream.Collector;
//import java.util.stream.Collectors;
//
//import com.intellij.openapi.actionSystem.AnAction;
//import com.intellij.openapi.actionSystem.AnActionEvent;
//import org.jetbrains.annotations.NotNull;
//
//public class GetSelectText extends AnAction {
//    @Override
//    public void actionPerformed(AnActionEvent event) {
//        final Editor editor = event.getData(LangDataKeys.EDITOR);
//        final Project project = event.getData(CommonDataKeys.PROJECT);
//        final Module module = event.getData(LangDataKeys.MODULE);
//        if (project != null && editor != null) {
//            final Document document = editor.getDocument();
//            FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
//            final SelectionModel selectionModel = editor.getSelectionModel();
//            final int start = selectionModel.getSelectionStart();
//            final int end = selectionModel.getSelectionEnd();
//            TextRange range = new TextRange(start, end);
//            //获取选中字符
//            String selectTxt = document.getText(range);
//
//            if (StringUtil.isNotEmpty(selectTxt)) {
////                System.out.println("选中内容：" + selectTxt);
//                Map<String, FileInfo> map = new HashMap<>();
//                VirtualFile currentFile = fileDocumentManager.getFile(document);
//                List<PsiFile> goFiles = findGoFile(project, module, selectTxt, currentFile.getName());
////                System.out.println("当前操作文件: " + currentFile);
//                goFiles.forEach(
//                        goFile -> {
//                            VirtualFile virtualFile = goFile.getVirtualFile();
//                            int offset = goFile.getText().indexOf("\"" + selectTxt + "\"");
//                            FileInfo fileInfo = new FileInfo();
//                            fileInfo.setOffset(offset);
//                            fileInfo.setProject(project);
//                            fileInfo.setVirtualFile(virtualFile);
//                            fileInfo.setFileName(virtualFile.getName());
//                            fileInfo.setCanonicalPath(goFile.getName());
//                            String[] keys = virtualFile.getCanonicalPath().split("/");
//                            String key = keys[keys.length - 2] + "/" + keys[keys.length - 1];
//                            map.put(key, fileInfo);
//                        }
//                );
//                usingUI(map, editor);
//
//            }
//
//        }
//
//
//    }
//
//    /**
//     * 找到对应的 go文件
//     */
//    private List<PsiFile> findGoFile(Project project, Module module, String router, String currentFileName) {
//        GlobalSearchScope moduleScope = GlobalSearchScope.moduleScope(module);
//        // FilenameIndex.getFilesByName(project, "", moduleScope);
//        ArrayList<PsiFile> psiFiles = new ArrayList<>();
//        Collection<VirtualFile> virtualFiles = FilenameIndex.getAllFilesByExt(project, "go", GlobalSearchScope.projectScope(project));
////        System.out.println("查找到的文件数量:" + virtualFiles.size());
//        for (VirtualFile virtualFile : virtualFiles) {
//
////            System.out.println("1.文件 " + virtualFile + "\n2.文件名 " + virtualFile.getName());
//
//            PsiManager psiManager = PsiManager.getInstance(project);
//            PsiFile file = psiManager.findFile(virtualFile);
//            String text = file.getText();
//            if (text != null) {
//                // 首次如果全匹配, 直接返回
//                // 没匹配的话先暂存起来
//                if (text.contains(router)) {
//                    String fileName = file.getName();
//                    String regex = "consts\\.ValidatorPrefix[\\s]{0,100}\\+[\\s]{0,100}\"" + router+"\"";
//                    Pattern r = Pattern.compile(regex);
//                    Matcher matcher = r.matcher(text);
//                    if (currentFileName.equals("api.go") || currentFileName.equals("web.go")) {
//                        //设置查找范围
//                        if (fileName.equals("api_register_validator.go") || fileName.equals("web_register_validator.go")) {
//                            if (matcher.find()) {
//                                psiFiles.add(file);
//                            }
//                        }
//                    } else if (currentFileName.equals("api_register_validator.go") || currentFileName.equals("web_register_validator.go")) {
//                        //设置查找范围
//                        if (fileName.equals("api.go") || fileName.equals("web.go")) {
//                            if (matcher.find()) {
//                                psiFiles.add(file);
//                            }
//                        }
//                    }
//
//                }
//            }
//        }
//
//        // 其他过滤匹配
//        return psiFiles;
//    }
//
//    /**
//     * 触发条件
//     */
//    @Override
//    public void update(final AnActionEvent e) {
//        //Get required data keys
//        final Project project = e.getProject();
//        final Editor editor = e.getData(CommonDataKeys.EDITOR);
//        //Set visibility only in case of existing project and editor and if some text in the editor is selected
//        e.getPresentation().setVisible((project != null && editor != null && editor.getSelectionModel().hasSelection()));
//    }
//
//    /**
//     * 加载UI
//     *
//     * @param
//     */
//    public static void usingUI(Map<String, FileInfo> fileInfoMap, Editor editor) {
//        List<String> list = fileInfoMap.entrySet().stream().map(
//                e -> e.getValue().getFileName() + "     " + e.getKey()).collect(Collectors.toList());
//        JBPopupFactory instance = JBPopupFactory.getInstance();// 创建实例
//        IPopupChooserBuilder<String> popupChooserBuilder = instance.createPopupChooserBuilder(list);
//        popupChooserBuilder.setItemChosenCallback(new Consumer<String>() {// 添加监听事件
//            @Override
//            public void consume(String s) {
//                FileInfo fileInfo = fileInfoMap.get(s.split("     ")[1]);
//                if (fileInfo != null) {
////                    System.out.println("FileInfo:" + fileInfo);
//                } else {
////                    System.out.println("空的");
//                }
//                new OpenFileDescriptor(fileInfo.getProject(), fileInfo.getVirtualFile(), fileInfo.getOffset()).navigate(true);
//            }
//        });
//
//        JBPopup popup = popupChooserBuilder.createPopup();
//        popup.showInBestPositionFor(editor);
//    }
//}
